<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表具号" prop="meterNo">
        <el-input v-model="queryParams.meterNo" placeholder="请输入表具号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="户号" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入户号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="户号" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="用户类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择用户类型" clearable>
          <el-option v-for="dict in dict.type.user_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="生产厂家" prop="maker">
        <el-select v-model="queryParams.maker" placeholder="请选择生产厂家" clearable>
          <el-option v-for="dict in dict.type.maker" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="表类型" prop="meterType">
      <el-select v-model="queryParams.meterType" placeholder="请选择表类型" clearable>
        <el-option v-for="dict in dict.type.meter_type" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
      </el-form-item>
      <el-form-item label="表状态" prop="meterState">
        <el-select v-model="queryParams.meterState" placeholder="请选择表状态" clearable>
          <el-option v-for="dict in dict.type.meter_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="价格编号" prop="priceCode">
        <el-input v-model="queryParams.priceCode" placeholder="请输入价格编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="价格设置" prop="priceCode">
        <el-select v-model="queryParams.priceCode" placeholder="请选择价格" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in priceConfigOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['installation:waterMeter:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['installation:waterMeter:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['installation:waterMeter:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['installation:waterMeter:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="waterMeterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="表具号" align="center" prop="meterNo" />
      <!-- <el-table-column label="户号" align="center" prop="userId" /> -->
      <el-table-column label="户号" align="center" prop="userId" :formatter="formatUser" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <!-- <el-table-column label="用户类型" align="center" prop="userType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_type" :value="scope.row.userType" />
        </template>
      </el-table-column> -->
      <el-table-column label="表类型" align="center" prop="meterType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.meter_type" :value="scope.row.meterType" />
        </template>
      </el-table-column>
      <el-table-column label="水表口径" align="center" prop="waterDiameter" />
      <el-table-column label="通水状态" align="center" prop="isSupply">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.supply_status" :value="scope.row.isSupply" />
        </template>
      </el-table-column>
      <el-table-column label="表状态" align="center" prop="meterState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.meter_state" :value="scope.row.meterState" />
        </template>
      </el-table-column>
      <el-table-column label="生产厂家" align="center" prop="maker">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.maker" :value="scope.row.maker" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="价格设置" align="center" prop="priceCode" /> -->
      <!-- <el-table-column label="价格设置" align="center" prop="priceCode"
        :formatter="(row) => formatPriceLabel(row.priceCode)">
      </el-table-column> -->
      <el-table-column label="安装地址" align="center" prop="address" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['installation:waterMeter:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['installation:waterMeter:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改表具信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表具号" prop="meterNo">
          <el-input v-model="form.meterNo" placeholder="请输入表具号" />
        </el-form-item>
        <el-form-item label="水表口径" prop="waterDiameter">
          <el-input v-model="form.waterDiameter" placeholder="请输入水表口径" />
        </el-form-item>
        <!-- <el-form-item label="户号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入户号" />
        </el-form-item> -->
        <el-form-item label="户号" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户" clearable filterable style="width: 100%">
            <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="表类型" prop="meterType">
          <el-select v-model="form.meterType" placeholder="请选择表类型">
            <el-option v-for="dict in dict.type.meter_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通水状态" prop="isSupply">
          <el-select v-model="form.isSupply" placeholder="请选择通水状态">
            <el-option v-for="dict in dict.type.supply_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表状态" prop="meterState">
          <el-select v-model="form.meterState" placeholder="请选择表状态">
            <el-option v-for="dict in dict.type.meter_state" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="价格编号" prop="priceCode">
          <el-input v-model="form.priceCode" placeholder="请输入价格编号" />
        </el-form-item> -->
        <!-- <el-form-item label="价格设置" prop="priceCode">
          <el-select v-model="form.priceCode" placeholder="请选择价格" clearable filterable style="width: 100%">
            <el-option v-for="item in priceConfigOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="生产厂家" prop="maker">
          <el-select v-model="form.maker" placeholder="请选择生产厂家">
            <el-option v-for="dict in dict.type.maker" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listWaterMeter, getWaterMeter, delWaterMeter, addWaterMeter, updateWaterMeter } from "@/api/installation/waterMeter";
  import { listPriceConfig } from "@/api/revenue/priceConfig";
  import { listWaterUser } from "@/api/installation/waterUser";

  export default {
    name: "WaterMeter",
    dicts: ['meter_type', 'user_type', 'meter_state', 'supply_status','maker'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表具信息表格数据
        waterMeterList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          meterNo: null,
          userId: null,
          userName: null,
          userType: null,
          meterType: null,
          meterState: null,
          priceCode: null,
          maker: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          meterNo: [
            { required: true, message: "表具号不能为空", trigger: "blur" }
          ],
          meterType: [
            { required: true, message: "表类型不能为空", trigger: "change" }
          ],
          meterState: [
            { required: true, message: "表状态不能为空", trigger: "change" }
          ],
        },
        priceConfigOptions: [],
        // 存储用户选项
        waterUserOptions: [],
        queryParamswaterUserOptions: {
          pageNum: 1,
          pageSize: 200,
        },
      };
    },
    created() {
      this.getList();
      this.getPriceConfigList();
      this.getWaterUserList();
    },
    methods: {
      /** 查询表具信息列表 */
      getList() {
        this.loading = true;
        listWaterMeter(this.queryParams).then(response => {
          this.waterMeterList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询价格列表 */
      getPriceConfigList() {
        listPriceConfig().then(response => {
          this.priceConfigOptions = response.rows.map(item => ({
            value: item.priceCode,
            label: item.priceName
          }));
        });
      },
      /** 查询用户列表 */
      getWaterUserList() {
        listWaterUser(this.queryParamswaterUserOptions).then(response => {
          this.waterUserOptions = response.rows.map(item => ({
            value: item.userId,
            label: item.userId
          }));
          // this.filteredWaterUserOptions = this.waterUserOptions;
        });
      },
      formatPriceLabel(value) {
        const option = this.priceConfigOptions.find(item => item.value === value);
        return option ? option.label : value;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          companyId: null,
          companyName: null,
          meterNo: null,
          userId: null,
          userName: null,
          userType: null,
          meterType: null,
          meterState: null,
          priceCode: null,
          waterDiameter: null,
          isSupply: null,
          address: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加表具信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getWaterMeter(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改表具信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateWaterMeter(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addWaterMeter(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除表具信息编号为"' + ids + '"的数据项？').then(function () {
          return delWaterMeter(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('installation/waterMeter/export', {
          ...this.queryParams
        }, `waterMeter_${new Date().getTime()}.xlsx`)
      }
      ,
      formatUser(row, column, cellValue) {
        const user = this.waterUserOptions.find(item =>
          String(item.value) === String(cellValue) // 统一转为字符串比较
        );
        return user?.label || `${cellValue}`; // 找不到时显示原始ID
      }
      ,
      formatUserName(row, column, cellValue) {
        const user = this.waterUserOptions.find(item =>
          String(item.value) === String(cellValue) // 统一转为字符串比较
        );
        return user?.label || `${cellValue}`; // 找不到时显示原始ID
      }
    }
  };
</script>
